package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.dialog.ImageSelectDialog;
import com.jiaoyou.baojian.dialog.YesOrNoDialog;
import com.jiaoyou.baojian.entity.UploadEntity;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.otto.AppBus;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.GlideCircleTransform;
import com.jiaoyou.baojian.utils.Utils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class EditUserInfoActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener, ImageSelectDialog.OnImageSelectListener {

    @BindView(R.id.header)
    ImageView header;
    @BindView(R.id.price)
    EditText price;
    @BindView(R.id.price_layout)
    RelativeLayout price_layout;
    @BindView(R.id.header1)
    ImageView header1;
    @BindView(R.id.header2)
    ImageView header2;
    @BindView(R.id.header3)
    ImageView header3;
    @BindView(R.id.header4)
    ImageView header4;
    @BindView(R.id.username)
    EditText username;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.info)
    EditText info;
    @BindView(R.id.save)
    Button save;

    private OptionsPickerView typePickerView;
    private TimePickerView birthdayPickerView;

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private CropOptions cropOptions;
    private Uri outputUri;
    private String headerUrl, header1Url, header2Url, header3Url, header4Url;
    private int indexHeader = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        cropOptions = getCropOptions();
        configTakePhotoOption();
        configCompress();

        setTitle("编辑个人资料");

        if(!TextUtils.isEmpty(getLoginResponse().userInfo.nickname))
            username.setText(getLoginResponse().userInfo.nickname);
        if(!TextUtils.isEmpty(getLoginResponse().userInfo.femaleType))
            type.setText(Utils.exchangeZhuboTypeString(getLoginResponse().userInfo.femaleType));
        if(!TextUtils.isEmpty(getLoginResponse().userInfo.birthday))
            birthday.setText(getLoginResponse().userInfo.birthday.substring(0, getLoginResponse().userInfo.birthday.indexOf(" ")));
        if(!TextUtils.isEmpty(getLoginResponse().userInfo.description))
            info.setText(getLoginResponse().userInfo.description);
        if(!TextUtils.isEmpty(getLoginResponse().userInfo.avatar)) {
            headerUrl = getLoginResponse().userInfo.avatar;
            Utils.showCircleImage(this, headerUrl, header);
        }
        price.setText(getLoginResponse().userInfo.costPerMin + "");
        if(getLoginResponse().userInfo.imageList != null){
            try{
                header1Url = getLoginResponse().userInfo.imageList.get(0);
                Utils.showImage(this, getLoginResponse().userInfo.imageList.get(0), header1);
            } catch (IndexOutOfBoundsException e){}
            try{
                header2Url = getLoginResponse().userInfo.imageList.get(1);
                Utils.showImage(this, getLoginResponse().userInfo.imageList.get(1), header2);
            } catch (IndexOutOfBoundsException e){}
            try{
                header3Url = getLoginResponse().userInfo.imageList.get(2);
                Utils.showImage(this, getLoginResponse().userInfo.imageList.get(2), header3);
            } catch (IndexOutOfBoundsException e){}
            try{
                header4Url = getLoginResponse().userInfo.imageList.get(3);
                Utils.showImage(this, getLoginResponse().userInfo.imageList.get(3), header4);
            } catch (IndexOutOfBoundsException e){}
        }

        if(!getLoginResponse().actress){
            type.setVisibility(View.GONE);
            price_layout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        takePhoto = getTakePhoto();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void initData() {
        final List<String> typeList = new ArrayList<>();
        typePickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                type.setText(typeList.get(options1));
            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("类型选择")
                .setSubCalSize(18)
                .setContentTextSize(18)
                .setCyclic(false, false, false)
                .setOutSideCancelable(true)
                .isDialog(false)
                .build();
        typeList.add("少妇");
        typeList.add("人妻");
        typeList.add("熟女");
        typeList.add("御姐");
        typeList.add("萝莉");
        typeList.add("OL");
        typePickerView.setPicker(typeList);


        birthdayPickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                birthday.setText(format.format(date));
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)
                .build();
        birthdayPickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    @Override
    public int getContentView() {
        return R.layout.activity_edit_user_info;
    }

    @OnClick({R.id.header, R.id.header1, R.id.header2, R.id.header3, R.id.header4, R.id.type, R.id.birthday, R.id.save})
    public void onViewClicked(View view) {
        Utils.hideKeyboard(header1, this);
        switch (view.getId()) {
            case R.id.header:
                indexHeader = 5;
                showImageSelectDialog(this);
                break;
            case R.id.header1:
                if(!TextUtils.isEmpty(header1Url)){
                    showYesOrNoDialog("是否确认删除该照片", "取消", "删除", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            header1Url = "";
                            header1.setImageResource(R.drawable.icon_edit_add);
                        }
                    });
                    return;
                }
                indexHeader = 1;
                showImageSelectDialog(this);
                break;
            case R.id.header2:
                if(!TextUtils.isEmpty(header2Url)){
                    showYesOrNoDialog("是否确认删除该照片", "取消", "删除", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            header2Url = "";
                            header2.setImageResource(R.drawable.icon_edit_add);
                        }
                    });
                    return;
                }
                indexHeader = 2;
                showImageSelectDialog(this);
                break;
            case R.id.header3:
                if(!TextUtils.isEmpty(header3Url)){
                    showYesOrNoDialog("是否确认删除该照片", "取消", "删除", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            header3Url = "";
                            header3.setImageResource(R.drawable.icon_edit_add);
                        }
                    });
                    return;
                }
                indexHeader = 3;
                showImageSelectDialog(this);
                break;
            case R.id.header4:
                if(!TextUtils.isEmpty(header4Url)){
                    showYesOrNoDialog("是否确认删除该照片", "取消", "删除", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            header4Url = "";
                            header4.setImageResource(R.drawable.icon_edit_add);
                        }
                    });
                    return;
                }
                indexHeader = 4;
                showImageSelectDialog(this);
                break;
            case R.id.type:
                typePickerView.show();
                break;
            case R.id.birthday:
                birthdayPickerView.show();
                break;
            case R.id.save:
                int headCount = 0;
                if(!TextUtils.isEmpty(header1Url)){
                    headCount++;
                }
                if(!TextUtils.isEmpty(header2Url)){
                    headCount++;
                }
                if(!TextUtils.isEmpty(header3Url)){
                    headCount++;
                }
                if(!TextUtils.isEmpty(header4Url)){
                    headCount++;
                }
                String[] url = new String[headCount];
                int index = 0;
                if(!TextUtils.isEmpty(header1Url)){
                    url[index++] = header1Url;
                }
                if(!TextUtils.isEmpty(header2Url)){
                    url[index++] = header2Url;
                }
                if(!TextUtils.isEmpty(header3Url)){
                    url[index++] = header3Url;
                }
                if(!TextUtils.isEmpty(header4Url)){
                    url[index++] = header4Url;
                }
                if(headCount == 0){
                    url = new String[1];
                    url[0] = "";
                }
                Api.getInstance().modifyUserInfo(
                        headerUrl,
                        url,
                        username.getEditableText().toString(),
                        getLoginResponse().userInfo.sex,
                        Utils.exchangeZhuboType(type.getText().toString()),
                        birthday.getText().toString(),
                        info.getEditableText().toString(),
                        Integer.parseInt(price.getText().toString()),
                        new BaofangCallback<String>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        toast("错误：" + t.getLocalizedMessage());
                    }

                    @Override
                    public void onSuccess(String s) {
                        toast("保存成功");
                        AppBus.getInstance().post(Event.EVENT_REFRESH_USERINFO);
                        onBackPressed();
                    }
                });
                break;
        }
    }

    @Override
    public void takeSuccess(final TResult result) {
        ///data/user/0/com.jiaoyou.baojian/cache/takephoto_cache/1494340603729.jpg
        waiting("上传图片...");
        Api.getInstance().uploadPhotoImage(new File(result.getImage().getCompressPath()), new BaofangCallback<UploadEntity>(){
            @Override
            public void onFailure(Call<BaseResponse<UploadEntity>> call, Throwable t) {
                stopWaiting();
                toast("上传失败：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(UploadEntity uploadEntity) {
                stopWaiting();
                switch (indexHeader){
                    case 1:
                        header1Url = uploadEntity.relativePath;
                        Glide.with(EditUserInfoActivity.this).load(result.getImage().getCompressPath()).crossFade().into(header1);
                        break;
                    case 2:
                        header2Url = uploadEntity.relativePath;
                        Glide.with(EditUserInfoActivity.this).load(result.getImage().getCompressPath()).crossFade().into(header2);
                        break;
                    case 3:
                        header3Url = uploadEntity.relativePath;
                        Glide.with(EditUserInfoActivity.this).load(result.getImage().getCompressPath()).crossFade().into(header3);
                        break;
                    case 4:
                        header4Url = uploadEntity.relativePath;
                        Glide.with(EditUserInfoActivity.this).load(result.getImage().getCompressPath()).crossFade().into(header4);
                        break;
                    case 5:
                        headerUrl = uploadEntity.relativePath;
                        Glide.with(EditUserInfoActivity.this).load(result.getImage().getCompressPath()).transform(new GlideCircleTransform(EditUserInfoActivity.this)).crossFade().into(header);
                        break;
                }
            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void takeCancel() {
//        Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(false);
        builder.setCorrectImage(true);
        getTakePhoto().setTakePhotoOptions(builder.create());
    }
    private void configCompress(){
        CompressConfig config;
        config = new CompressConfig.Builder()
                .setMaxSize(100 * 1024)
                .setMaxPixel(600)
                .enableReserveRaw(true)
                .create();
        getTakePhoto().onEnableCompress(config, true);
    }
    private CropOptions getCropOptions(){
        CropOptions.Builder builder=new CropOptions.Builder();
        builder.setAspectX(1).setAspectY(1);
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }
    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }
    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    @Override
    public void onSelectCamera() {
        generalOutputUri();
        getTakePhoto().onPickFromCaptureWithCrop(outputUri, cropOptions);
    }

    @Override
    public void onSelectGallery() {
        generalOutputUri();
        getTakePhoto().onPickFromGalleryWithCrop(outputUri, cropOptions);
    }

    private void generalOutputUri(){
        configCompress();
        File file = Utils.generalTempFile(".jpg");
        outputUri = Uri.fromFile(file);
    }
}
